﻿using Dralee.App;
using Grpc.Core;

namespace Net02_Grpc_Server
{
    public class CalculatorService : Calculator.CalculatorBase
    {
        private readonly ILogger _logger;
        public CalculatorService(ILogger<CalculatorService> logger)=> _logger = logger;

        public override Task<OutputMessage> Add(InputMessage request, ServerCallContext context) => InvokeAsync((op1, op2) => op1 + op2, request);
        public override Task<OutputMessage> Substract(InputMessage request, ServerCallContext context) => InvokeAsync((op1, op2) => op1 - op2, request);
        public override Task<OutputMessage> Multiply(InputMessage request, ServerCallContext context) => InvokeAsync((op1, op2) => op1 * op2, request);
        public override Task<OutputMessage> Divide(InputMessage request, ServerCallContext context) => InvokeAsync((op1, op2) => op1 / op2, request);

        private Task<OutputMessage> InvokeAsync(Func<int, int, int> calculate, InputMessage request)
        {
            OutputMessage output;
            try
            {
                output = new OutputMessage { Status = 0, Result = calculate(request.X, request.Y) };
            }catch(Exception ex)
            {
                _logger.LogError(ex, "Calculation error.");
                output = new OutputMessage {  Status = 1, Error = ex.ToString() };
            }
            return Task.FromResult(output);
        }
    }
}
